function results = wireless_network_queuing(varargin)
% 无线分组网络中的排队分析函数
% 功能：分析无线网络中的排队性能，考虑拓扑结构和干扰
%
% 输入参数：
%   'flow_rates' - 流量强度向量 (默认: 0.1:0.1:0.8)
%   'network_size' - 网络大小 (默认: 5)
%   'transmission_range' - 传输范围 (默认: 1.0)
%   'plot_results' - 是否绘制结果 (默认: true)
%
% 输出：
%   results - 包含分析结果的结构体
%
% 示例：
%   results = wireless_network_queuing('flow_rates', 0.1:0.1:0.8, 'network_size', 5);

% 参数解析
p = inputParser;
addParameter(p, 'flow_rates', 0.1:0.1:0.8);
addParameter(p, 'network_size', 5);
addParameter(p, 'transmission_range', 1.0);
addParameter(p, 'plot_results', true);
parse(p, varargin{:});

flow_rates = p.Results.flow_rates;
network_size = p.Results.network_size;
transmission_range = p.Results.transmission_range;
plot_results = p.Results.plot_results;

% 添加路径
addpath('../Common');

% 获取颜色定义
colors = color_definitions();

fprintf('=== 无线分组网络中的排队分析 ===\n');

% 无线Ad hoc网络中的排队
% 考虑干扰和竞争的网络模型
node_positions = rand(network_size, 2) * 10; % 节点位置 (随机分布)

% 计算邻接矩阵
adjacency_matrix = zeros(network_size, network_size);
for i = 1:network_size
    for j = 1:network_size
        if i ~= j
            distance = norm(node_positions(i, :) - node_positions(j, :));
            if distance <= transmission_range
                adjacency_matrix(i, j) = 1;
            end
        end
    end
end

% 网络流量模型
network_delays = zeros(length(flow_rates), 1);
network_throughputs = zeros(length(flow_rates), 1);

for flow_idx = 1:length(flow_rates)
    lambda_flow = flow_rates(flow_idx);
    
    % 简化的网络排队模型
    % 考虑竞争和干扰的影响
    
    % 计算网络容量 (最大流最小割定理)
    network_capacity = estimate_network_capacity(adjacency_matrix);
    
    % 有效服务率 (考虑竞争)
    effective_service_rate = network_capacity * exp(-lambda_flow / network_capacity);
    
    if lambda_flow < effective_service_rate
        % 网络平均时延
        network_delay = 1 / (effective_service_rate - lambda_flow);
        network_throughput = lambda_flow;
    else
        network_delay = inf;
        network_throughput = 0;
    end
    
    network_delays(flow_idx) = network_delay;
    network_throughputs(flow_idx) = network_throughput;
end

% 不同网络规模的影响
network_sizes = [3, 5, 7, 10];
network_scaling_delays = zeros(length(flow_rates), length(network_sizes));

for size_idx = 1:length(network_sizes)
    net_size = network_sizes(size_idx);
    node_pos = rand(net_size, 2) * 10;
    
    % 重新计算邻接矩阵
    adj_matrix = zeros(net_size, net_size);
    for i = 1:net_size
        for j = 1:net_size
            if i ~= j
                dist = norm(node_pos(i, :) - node_pos(j, :));
                if dist <= transmission_range
                    adj_matrix(i, j) = 1;
                end
            end
        end
    end
    
    % 计算性能
    for flow_idx = 1:length(flow_rates)
        lambda_flow = flow_rates(flow_idx);
        net_capacity = estimate_network_capacity(adj_matrix);
        effective_mu = net_capacity * exp(-lambda_flow / net_capacity);
        
        if lambda_flow < effective_mu
            network_scaling_delays(flow_idx, size_idx) = 1 / (effective_mu - lambda_flow);
        else
            network_scaling_delays(flow_idx, size_idx) = inf;
        end
    end
end

% 传输范围的影响
transmission_ranges = [0.5, 1.0, 1.5, 2.0];
range_delays = zeros(length(flow_rates), length(transmission_ranges));

for range_idx = 1:length(transmission_ranges)
    tx_range = transmission_ranges(range_idx);
    
    % 重新计算邻接矩阵 (固定节点位置)
    adj_matrix = zeros(network_size, network_size);
    for i = 1:network_size
        for j = 1:network_size
            if i ~= j
                dist = norm(node_positions(i, :) - node_positions(j, :));
                if dist <= tx_range
                    adj_matrix(i, j) = 1;
                end
            end
        end
    end
    
    % 计算性能
    for flow_idx = 1:length(flow_rates)
        lambda_flow = flow_rates(flow_idx);
        net_capacity = estimate_network_capacity(adj_matrix);
        effective_mu = net_capacity * exp(-lambda_flow / net_capacity);
        
        if lambda_flow < effective_mu
            range_delays(flow_idx, range_idx) = 1 / (effective_mu - lambda_flow);
        else
            range_delays(flow_idx, range_idx) = inf;
        end
    end
end

% 网络容量分析
network_capacities = zeros(1, length(transmission_ranges));
for range_idx = 1:length(transmission_ranges)
    tx_range = transmission_ranges(range_idx);
    adj_matrix = zeros(network_size, network_size);
    for i = 1:network_size
        for j = 1:network_size
            if i ~= j
                dist = norm(node_positions(i, :) - node_positions(j, :));
                if dist <= tx_range
                    adj_matrix(i, j) = 1;
                end
            end
        end
    end
    network_capacities(range_idx) = estimate_network_capacity(adj_matrix);
end

% 绘制结果
if plot_results
    figure('Name', '无线网络排队分析', 'Position', [250, 250, 1200, 800]);
    
    subplot(2,3,1);
    plot(node_positions(:, 1), node_positions(:, 2), 'ro', 'MarkerSize', 8, 'MarkerFaceColor', 'r');
    grid on;
    hold on;
    for i = 1:network_size
        for j = i+1:network_size
            if adjacency_matrix(i, j) == 1
                plot([node_positions(i, 1), node_positions(j, 1)], ...
                     [node_positions(i, 2), node_positions(j, 2)], 'k-', 'LineWidth', 1);
            end
        end
    end
    title('网络拓扑');
    xlabel('X坐标');
    ylabel('Y坐标');
    
    subplot(2,3,2);
    plot(flow_rates, network_delays, 'b-o', 'LineWidth', 2);
    grid on;
    xlabel('流量强度');
    ylabel('网络平均时延');
    title('网络时延性能');
    
    subplot(2,3,3);
    plot(flow_rates, network_throughputs, 'r-s', 'LineWidth', 2);
    grid on;
    xlabel('流量强度');
    ylabel('网络吞吐量');
    title('网络吞吐量性能');
    
    subplot(2,3,4);
    for size_idx = 1:length(network_sizes)
        plot(flow_rates, network_scaling_delays(:, size_idx), ...
             ['-', colors(size_idx)], 'LineWidth', 2);
        hold on;
    end
    grid on;
    xlabel('流量强度');
    ylabel('网络时延');
    title('网络规模对时延的影响');
    legend(arrayfun(@(x) sprintf('%d节点', x), network_sizes, 'UniformOutput', false));
    
    subplot(2,3,5);
    for range_idx = 1:length(transmission_ranges)
        plot(flow_rates, range_delays(:, range_idx), ...
             ['-', colors(range_idx)], 'LineWidth', 2);
        hold on;
    end
    grid on;
    xlabel('流量强度');
    ylabel('网络时延');
    title('传输范围对时延的影响');
    legend(arrayfun(@(x) sprintf('%.1f', x), transmission_ranges, 'UniformOutput', false));
    
    subplot(2,3,6);
    bar(network_capacities);
    grid on;
    title('网络容量 vs 传输范围');
    xlabel('传输范围');
    ylabel('网络容量');
    set(gca, 'XTickLabel', arrayfun(@(x) sprintf('%.1f', x), transmission_ranges, 'UniformOutput', false));
end

% 组织结果
results = struct();
results.flow_rates = flow_rates;
results.network_size = network_size;
results.transmission_range = transmission_range;
results.node_positions = node_positions;
results.adjacency_matrix = adjacency_matrix;
results.network_delays = network_delays;
results.network_throughputs = network_throughputs;
results.network_sizes = network_sizes;
results.network_scaling_delays = network_scaling_delays;
results.transmission_ranges = transmission_ranges;
results.range_delays = range_delays;
results.network_capacities = network_capacities;
results.colors = colors;

fprintf('无线分组网络中的排队分析完成\n');
end

%% 辅助函数
function network_capacity = estimate_network_capacity(adjacency_matrix)
    % 简化的网络容量估计
    % 基于最大流最小割定理的近似
    
    num_nodes = size(adjacency_matrix, 1);
    max_flows = zeros(num_nodes, 1);
    
    for source = 1:num_nodes
        for sink = 1:num_nodes
            if source ~= sink
                % 简化计算：最短路径作为容量估计
                [path, ~] = find_shortest_path(adjacency_matrix, source, sink);
                if ~isempty(path)
                    path_capacity = length(path) - 1; % 路径长度作为容量度量
                    max_flows(source) = max_flows(source) + path_capacity;
                end
            end
        end
    end
    
    network_capacity = mean(max_flows);
end

function [path, distance] = find_shortest_path(adj_matrix, source, sink)
    % 简化的最短路径算法 (Dijkstra算法的近似)
    num_nodes = size(adj_matrix, 1);
    distances = inf(1, num_nodes);
    visited = false(1, num_nodes);
    previous = zeros(1, num_nodes);
    
    distances(source) = 0;
    
    for i = 1:num_nodes
        % 找到未访问的最小距离节点
        [~, u] = min(distances + inf * visited);
        if isinf(distances(u))
            break;
        end
        visited(u) = true;
        
        % 更新邻居距离
        neighbors = find(adj_matrix(u, :) == 1);
        for v = neighbors'
            alt = distances(u) + 1; % 单位距离
            if alt < distances(v)
                distances(v) = alt;
                previous(v) = u;
            end
        end
    end
    
    % 重构路径
    if distances(sink) < inf
        path = sink;
        u = sink;
        while u ~= source
            u = previous(u);
            path = [u, path];
        end
        distance = distances(sink);
    else
        path = [];
        distance = inf;
    end
end